<?php
require_once ('library/Model/BaseModel.php');

/**
 *
 * @author Nguyen
 *        
 */
class Company extends BaseModel implements IModel {
	/**
	 * View Render
	 *
	 * @var ViewRender
	 */
	private $_view;
	/**
	 *
	 * @return ViewRender
	 * 
	 */
	public function view() {
		return $this->_view;
	}
	public function getallNameCompany() {
		$sql = 'select id,name from company where status = 1';
		return $this->db->fetchAll ( $sql );
	}
	/*
	 * (non-PHPdoc) @see BaseModel::insert()
	 */
	public function insert(array $entity) {
		// TODO Auto-generated method stub
		$entity ['code'] = $this->generateCode ( $entity ['name'] );
		$sql = "insert into company (";
		$c = $b = 0;
		foreach ( $entity as $key => $value ) {
			if ($c == 0) {
				$sql .= $key;
				$c = 1;
			} else
				$sql .= "," . $key;
		}
		$sql .= ")";
		$sql .= " values (";
		foreach ( $entity as $key => $value ) {
			if ($b == 0) {
				$sql .= "'" . $value . "'";
				$b = 1;
			} else
				$sql .= "," . "'" . $value . "'";
		}
		$sql .= ")";
		return $this->db->execute ( $sql );
	}
	/*
	 * (non-PHPdoc) @see BaseModel::generateCode()
	 */
	public function generateCode($key) {
		// TODO Auto-generated method stub
		$code = strtoupper ( substr ( $key, 0, 1 ) );
		$sql = 'select code from company';
		$list = $this->db->fetchAll ( $sql );
		$c = 0;
		foreach ( $list as $en ) {
			$temp = strtoupper ( substr ( $en ['code'], 0, 1 ) );
			if ($code == $temp)
				$c += 1;
		}
		if ($c == 0)
			return $code = $code . '1';
		else {
			$sql1 = 'select code from company where code like "' . $code . '%" order by code DESC limit 0,1';
			$x = $this->db->fetchRow ( $sql1 );
			$x = intval(substr($x['code'], 1, strlen($x['code']))) + 1;
			if ($x < 10) {
				return $code = $code.'0'. $x;
			}
			return $code = $code . $x;
		}
	}
	/* (non-PHPdoc)
	 * @see BaseModel::update()
	 */
	public function update(array $entity) {
		// TODO Auto-generated method stub
		$id = $entity ['id'];
		$xsql = 'select name from company where id = '.$id;
		$xxx = $this->db->fetchRow($xsql);
		if ($xxx['name'] != $entity['name']) {
			$entity['code'] = $this->generateCode($entity['name']);
		}
		iDebug::debugArray($entity);
		$entity = iArray::removeAtTop ( $entity, 1 );
		$b = sizeof ( $entity );
		$c = 0;
		$sql = "update company set ";
		foreach ( $entity as $key => $value ) {
			$c += 1;
			if ($b == $c)
				$sql .= $key . " = " . "'" . $value . "'";
			else
				$sql .= $key . " = " . "'" . $value . "'" . ",";
		}
		$sql .= " where id = " . $id;
		echo $sql;
		return $this->db->execute ( $sql );
	}
	public function getNameByid($id){
		$sql = 'select name from company where id = '.$id;
		$x = $this->db->fetchRow($sql);
		return $x['name'];
	}
}

?>